/*!
 * jQuery simpleEdit Plugin 
 * V 1.0
 * copyright http://saquery.com
 *
 */
(function($){
	$.fn.simpleEdit = function( ) {
		return $(this).keydown(function(e){
			if (e.which==9 && !e.ctrlKey && !e.altKey) {
				var 
				_get =function(ctrl) {
					if (ctrl.selectionStart) {
						return ctrl.selectionStart;
					} else if (!document.selection) {
						return 0;
					};
					var
						c = "\001",
						sel = document.selection.createRange(),
						dul = sel.duplicate(),
						len = 0;

					dul.moveToElementText(ctrl);
					sel.text = c;
					len = dul.text.indexOf(c);
					sel.moveStart('character',-1);
					sel.text = "";
					return len;
				},
				_set=function(ctrl, pos){
					if(ctrl.setSelectionRange){
						ctrl.focus();
						ctrl.setSelectionRange(pos,pos);
					}
					else if (ctrl.createTextRange) {
						var range = ctrl.createTextRange();
						range.collapse(true);
						range.moveEnd('character', pos);
						range.moveStart('character', pos);
						range.select();
					}
				}/*,
				_prevEnterPos=function(v, pos){
					var 
						_result = pos-1;
					while( v.substring(_result,_result+1)!='\n' && _result>=0) 
						_result--;
					return _result;
				}*/,
				_insert=function(v,pos){
					return _v.substring(0, pos)+ '\t'+ _v.substring(pos, _v.length);
				},
				_del=function(v){
					if (v[v.length-1]=='\t') v = v.substring(0,v.length-1);
					return v;
				},
				_delete=function(v,pos){					
					return _del(_v.substring(0, pos)) + _v.substring(pos, _v.length);
				},_v,_pos,_lines;

			_v = $(this).val();
			_pos=_get(this);
			_lines = _v.substring(0, _pos).match(/\n/g);
			
			if (_lines!=null) {
				//document.title=_prevEnterPos(_v,_pos)
				_lines=_lines.length;
			}
			
			// FIX IE Behavior. Don' t know... seems like '\n' != '\n' for IE.
			if ($.browser.msie) _pos = _pos-_lines;
			
			if (e.shiftKey){
				$(this).val( _delete(_v,_pos) );
				_pos--;
			}else {	
				$(this).val( _insert(_v,_pos) );
				_pos++;
			}				
			_set(this,_pos);
			e.preventDefault();
		}});
	};
})(jQuery);